<template>
  <div class="box">
    <el-card class="card-css">
      <div class="zhpj">
        <span class="zhpj-span">报表打印</span>
      </div>

      <div class="table-css">
        <div class="btn-css">
          <el-button type="success" @click="machine_data">设备数据</el-button>
          <el-button type="success" @click="operating_data">运行数据</el-button>
          <el-button type="success" @click="qualified">能耗能效</el-button>
          <el-button type="success" @click="dialogVisible = !dialogVisible"
            >自定义</el-button
          >
        </div>

        <div class="select02">
          <el-select placeholder="一小时">
            <el-option label="一分钟" value="shanghai" />
            <el-option label="五分钟" value="beijing" />
            <el-option label="一小时" value="beijing" />
            <el-option label="一天" value="beijing" />
            <el-option label="一月" value="beijing" />
          </el-select>
        </div>

        <div class="block">
          <el-date-picker
            v-model="dateValue"
            type="daterange"
            range-separator="至"
            start-placeholder="开始时间"
            :disabled-date="(time) => time.getTime() > Date.now()"
            end-placeholder="结束时间"
          />
        </div>

        <div class="btn-01">
          <el-button type="primary" @click="exportExcel">下 载</el-button>
        </div>
        <!-- <div class="btn-02">
					<el-button type="primary">打 印</el-button>
				</div> -->
      </div>

      <div class="table" v-if="tableStatus == 'machineData'">
        <el-table
          id="table"
          :row-key="getRowKeys"
          :data="tableData"
          style="width: 100%; height: 350px"
          :header-cell-style="{
            'text-align': 'center',
            background: '#B4C7E7',
            color: '#333333',
          }"
          :cell-style="{
            'text-align': 'center',
            background: '#f5f8fb',
          }"
        >
          <el-table-column v-if="midData.show" width="150" label="时间">
            <template #default="scope">
              <span>{{ dayjs(scope.row.createTime).format("YY-MM-DD") }}</span>
            </template>
          </el-table-column>
          <el-table-column
            v-for="item in midData.refrigerator"
            :key="item.id"
            :label="item.label"
          >
            <el-table-column
              v-for="(opt, index) in item.children"
              :key="index"
              :prop="opt.prop"
              :label="opt.label"
              ><template v-slot:header
                >{{ opt.label }}
              </template></el-table-column
            >

            <template v-slot:header>{{ item.label }} </template>
          </el-table-column>
        </el-table>
        <!-- <div class="pagination">
					<el-pagination
						layout="prev, pager, next, jumper"
						:total="1000"
						@size-change="handleSizeChange"
						@current-change="handleCurrentChange"
					/>
				</div> -->
      </div>

      <div class="table" v-else-if="tableStatus == 'operatingData'">
        <el-table
          :data="tableDataOperating"
          style="width: 100%"
          border
          :row-key="getRowKeys"
          :header-cell-style="{
            'text-align': 'center',
            background: '#B4C7E7',
            color: '#333333',
          }"
          :cell-style="{
            'text-align': 'center',
            background: '#f5f8fb',
          }"
        >
          <el-table-column v-if="midData.show" label="时间">
            <template #default="scope">
              <span>{{ dayjs(scope.row.createTime).format("YY-MM-DD") }}</span>
            </template>
          </el-table-column>
          <el-table-column
            v-for="(i, idx) in midData.runtime"
            :key="idx"
            :prop="i.prop"
            :label="i.label"
          >
            <el-table-column
              v-for="(opt, index) in i.children"
              :key="index"
              :prop="opt.prop"
              :label="opt.label"
              ><template v-slot:header>{{ opt.label }} </template>
            </el-table-column>
            <template v-slot:header>{{ i.label }} </template>
          </el-table-column>
        </el-table>
        <!-- <div class="pagination">
					<el-pagination
						v-model:page-size="pageSize3"
						layout="prev, pager, next, jumper"
						:total="1000"
						@size-change="handleSizeChange"
						@current-change="handleCurrentChange"
					/>
				</div> -->
      </div>

      <div class="table" v-else-if="tableStatus == 'qualified'">
        <el-table
          :data="tableDataQualified"
          :row-key="getRowKeys"
          style="width: 100%"
          border
          :header-cell-style="{
            'text-align': 'center',
            background: '#B4C7E7',
            color: '#333333',
          }"
          :cell-style="{
            'text-align': 'center',
            background: '#f5f8fb',
          }"
        >
          <el-table-column v-if="midData.show" label="时间">
            <template #default="scope">
              <span>{{
                dayjs(scope.row.createTime).format("YYYY-MM-DD")
              }}</span>
            </template>
          </el-table-column>
          <el-table-column
            v-for="(item, i) in midData.energy"
            :key="i"
            :prop="item.prop"
            :label="item.label"
          >
            <template v-slot:header>{{ item.label }} </template>
          </el-table-column>
        </el-table>
        <!-- <div class="pagination">
					<el-pagination
						v-model:page-size="pageSize3"
						layout="prev, pager, next, jumper"
						:total="1000"
						@size-change="handleSizeChange"
						@current-change="handleCurrentChange"
					/>
				</div> -->
      </div>
    </el-card>
    <!-- 自定义弹框 -->
    <el-dialog
      v-model="dialogVisible"
      append-to-body
      title="自定义"
      ref="dialog"
      @open="open"
      width="504px"
    >
      <div class="checkbox-div">
        <div>
          <el-checkbox v-model="ckAll" label="全选" />
        </div>
        <div>
          <el-checkbox v-model="ShowTime" label="时间" size="large" />
        </div>
        <div>设备数据</div>

        <div>
          <el-tree
            :data="testdata11"
            ref="tree"
            show-checkbox
            node-key="id"
            :props="defaultProps"
          >
          </el-tree>
        </div>
        <div>运行数据</div>

        <div>
          <el-checkbox-group v-model="checked1">
            <el-checkbox
              size="large"
              v-for="(item, index) in state.yunxing"
              :key="index"
              :label="item.label"
            >
              {{ item.label }}
            </el-checkbox>
          </el-checkbox-group>
        </div>

        <div>能耗能效</div>
        <div>
          <el-checkbox-group v-model="checked2">
            <el-checkbox
              size="large"
              v-for="(item, index) in state.nenghao"
              :key="index"
              :label="item.label"
            >
              {{ item.label }}
            </el-checkbox>
          </el-checkbox-group>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false" class="quxiao-btn"
            >取消</el-button
          >
          <el-button type="primary" @click="saveProp" class="sava-btn"
            >保存</el-button
          >
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { onMounted, reactive, ref, computed, toRaw } from "vue";
import { YunXing, Lengji } from "@/api/model/end";
import FileSaver from "file-saver";
import * as XLSX from "xlsx/dist/xlsx.mini.min.js";
import dayjs from "dayjs";
const tableStatus = ref("machineData");
let dialogVisible = ref(false);

// 树形控件的实例
let tree = ref(null);
let dateValue = ref("");
let dialog = ref(null);
const defaultProps = {
  children: "children",
  label: "label",
};
// 控制三个时间字段的显示
let ShowTime = ref();
// 给table 一个key值 防止复用
const getRowKeys = (row) => {
  return row.id;
};
// const handleSizeChange = (val) => {
// 	console.log(`${val} items per page`);
// };
// const handleCurrentChange = (val) => {
// 	console.log(`current page: ${val}`);
// };
// 运行数据的选择项
const checked1 = ref([]);
// 能耗能效的选择项
const checked2 = ref([]);
// 全选和反选
const ckAll = computed({
  get() {
    //
    return (
      checked1.value.length === 6 &&
      checked2.value.length === 11 &&
      ShowTime.value.every((i) => i) &&
      tree.value.getCheckedNodes().filter((i) => i.children).length === 4
    );
  },
  set(val) {
    if (val) {
      console.log(tree.value.getCheckedNodes());
      tree.value.setCheckedNodes(testdata11.value);
      checked1.value = state.yunxing.map((i) => i.label);
      checked2.value = state.nenghao.map((i) => i.label);
      ShowTime.value = true;
    } else {
      tree.value.setCheckedKeys([], false);
      checked1.value = [];
      checked2.value = [];
      ShowTime.value = false;
    }
  },
});

let testdata = ref([
  {
    id: "1",
    label: "冷机运行功率",
    children: [
      {
        id: "5",
        label: "1#",
        prop: "statusOne",
      },
      {
        id: "6",
        label: "2#",
        prop: "statusTwo",
      },
      {
        id: "7",
        label: "3#",
        prop: "statusThree",
      },
      {
        id: "8",
        label: "4#",
        prop: "statusFour",
      },
    ],
  },
  {
    id: "2",
    label: "冷冻泵运行功率",
    prop: "freezingPump",
    // children: [
    // 	{
    // 		id: "8",
    // 		label: "1#",
    // 		prop: "ratingOne",
    // 	},
    // 	{
    // 		id: "9",
    // 		label: "2#",
    // 		prop: "ratingTwo",
    // 	},
    // 	{
    // 		id: "10",
    // 		label: "3#",
    // 		prop: "ratingThree",
    // 	},
    // ],
  },
  {
    id: "3",
    label: "冷却泵运行功率",
    prop: "coolingPump",
    // children: [
    // 	{
    // 		id: "11",
    // 		label: "1#",
    // 		prop: "temperatureOne",
    // 	},
    // 	{
    // 		id: "12",
    // 		label: "2#",
    // 		prop: "temperatureTwo",
    // 	},
    // 	{
    // 		id: "13",
    // 		label: "3#",
    // 		prop: "temperatureThree",
    // 	},
    // ],
  },
  {
    id: "4",
    label: "冷却塔运行功率",
    prop: "coolingTower",
    // children: [
    // 	{
    // 		id: "14",
    // 		label: "1#",
    // 		prop: "loadOne",
    // 	},
    // 	{
    // 		id: "15",
    // 		label: "2#",
    // 		prop: "loadTwo",
    // 	},
    // 	{
    // 		id: "16",
    // 		label: "3#",
    // 		prop: "loadThree",
    // 	},
    // ],
  },
]);

let testdata11 = ref([
  {
    id: "1",
    label: "冷机运行功率",
  },
  {
    id: "2",
    label: "冷冻泵运行功率",
  },
  {
    id: "3",
    label: "冷却泵运行功率",
  },
  {
    id: "4",
    label: "冷却塔运行功率",
  },
]);
const tableData = ref([
  {
    date: "2016-05-03",
    status_one: "关",
    status_two: "关",
    status_three: "关",
    power_one: "0.573",
    power_two: "0.573",
    power_three: "0.573",
    temperature_one: "21.83",
    temperature_two: "21.83",
    temperature_three: "21.83",
    load_one: "0.000",
    load_two: "0.000",
    load_three: "0.000",
  },
]);

const tableDataOperating = ref([
  {
    date: "2016-05-03",
    water: "21.86",
    backwater: "21.86",
    onewater: "21.86",
    twowater: "21.86",
    power: "21.86",
    efficiency: "21.86",
  },
]);

const tableDataQualified = ref([
  {
    date: "2016-05-03",
    energy: "0.000",
    refrigerating: "0.000",
    computerroom: "0.000",
    machineefficiency: "0.000",
    afrozen: "0.000",
    refrigeran: "0.000",
    pumpefficiency: "0.000",
    towerefficiency: "0.000",
    average_temperature: "0.000",
    minimum_temperature: "0.000",
    maximum_temperature: "0.000",
  },
]);

const state = reactive({
  yunxing: [
    {
      id: "1",
      label: "冷冻供水温度（℃）",
      children: [
        {
          id: "10",
          label: "总管",
          prop: "cswtManager",
        },
        {
          id: "11",
          label: "T1",
          prop: "cswtT1",
        },
        {
          id: "12",
          label: "T2",
          prop: "cswtT2",
        },
        {
          id: "13",
          label: "裙房",
          prop: "cswtPodiums",
        },
      ],
    },
    {
      id: "2",
      label: "冷冻回水温度（℃）",
      children: [
        {
          id: "14",
          label: "总管",
          prop: "rcwtManager",
        },
        {
          id: "15",
          label: "T1",
          prop: "rcwtT1",
        },
        {
          id: "16",
          label: "T2",
          prop: "rcwtT2",
        },
        {
          id: "17",
          label: "裙房",
          prop: "rcwtPodiums",
        },
      ],
    },
    {
      id: "3",
      label: "冷冻流量（㎡/h）",
    },
    {
      id: "4",
      label: "冷机冷却进水温度",
    },
    {
      id: "5",
      label: "冷机冷却回水温度",
    },
    {
      id: "6",
      label: "热水一次侧（℃）",
      children: [
        {
          id: "18",
          label: "供水",
          prop: "waterSupply",
        },
        {
          id: "19",
          label: "回水",
          prop: "backwater",
        },
      ],
    },
    {
      id: "7",
      label: "热水二次侧供水温度（℃）",
      children: [
        {
          id: "20",
          label: "总管",
          prop: "wstotshwManager",
        },
        {
          id: "21",
          label: "T1",
          prop: "wstotshwT1",
        },
        {
          id: "22",
          label: "T2",
          prop: "wstotshwT2",
        },
        {
          id: "23",
          label: "裙房",
          prop: "wstotshwPodiums",
        },
      ],
    },
    {
      id: "8",
      label: "热水二次侧回水温度（℃）",
      children: [
        {
          id: "24",
          label: "总管",
          prop: "totsrwohwManager",
        },
        {
          id: "25",
          label: "T1",
          prop: "totsrwohwT1",
        },
        {
          id: "26",
          label: "T2",
          prop: "totsrwohwT2",
        },
        {
          id: "27",
          label: "裙房",
          prop: "totsrwohwpodiums",
        },
      ],
    },
    {
      id: "9",
      label: "热水流量（㎡/h）",
      prop: "hotWaterFlowRate",
    },
  ],

  nenghao: [
    {
      label: "冷机能耗(kWh)",
      prop: "coldMachine",
    },
    {
      label: "冷冻泵能耗(kWh)",
      prop: "freezingPump",
    },
    {
      label: "冷却泵能耗(kWh)",
      prop: "coolingPump",
    },
    {
      label: "冷却塔能耗(kWh)",
      prop: "coolingTower",
    },
    {
      label: "热水泵能耗(kWh)",
      prop: "hotWaterPump",
    },
    {
      label: "制冷量(kW)",
      prop: "refrigeratingCapacity",
    },
    {
      label: "冷机COP",
      prop: "refrigeratorCOP",
    },
    {
      label: "机房COP",
      prop: "psychzCOP",
    },
  ],
});
// 最终展示字段的数据
let midData = reactive({
  refrigerator: JSON.parse(localStorage.getItem("test")) || testdata.value,
  runtime: JSON.parse(localStorage.getItem("run")) || toRaw(state.yunxing),
  energy: JSON.parse(localStorage.getItem("energy")) || toRaw(state.nenghao),
  show: JSON.parse(localStorage.getItem("showTime")) || true,
});

// dialog 没有打开时默认不渲染 需要在打开创建的时候赋值
const open = () => {
  ShowTime.value = JSON.parse(localStorage.getItem("showTime"));
  tree.value.setCheckedNodes(midData.refrigerator);
  console.log(tree.value.getCheckedNodes());
  checked1.value = midData.runtime.map((i) => i.label);
  checked2.value = midData.energy.map((i) => i.label);
};
// 将选中的菜单 存储到本地存储中
const saveProp = () => {
  localStorage.setItem("showTime", JSON.stringify(ShowTime.value));
  localStorage.setItem(
    "energy",
    JSON.stringify(
      state.nenghao.filter((i) => {
        if (checked2.value.find((opt) => opt === i.label)) {
          return i;
        }
      })
    )
  );
  localStorage.setItem(
    "run",
    JSON.stringify(
      state.yunxing.filter((i) => {
        if (checked1.value.find((opt) => opt === i.label)) {
          return i;
        }
      })
    )
  );
  // 处理选择的节点数据
  // let col = tree.value
  //   // 获取包括半选节点
  //   .getCheckedNodes(false, true)
  //   .filter((i) => i.children)
  //   .map((item) => {
  //     item.children = item.children.filter((leaf) => {
  //       if (
  //         // 获取所有被选择的子节点
  //         tree.value.getCheckedKeys(true).find((id) => id == leaf.id)
  //       ) {
  //         return leaf;
  //       }
  //     });
  //     return item;
  //   });
  let col = tree.value
    // 获取包括半选节点
    .getCheckedNodes(false, false)
    .map((item) => {
      return testdata.value.find((i) => i.id === item.id);
    });
  localStorage.setItem("test", JSON.stringify(col));
  setData();
  dialogVisible.value = false;
};
// 保存之后从本地存储中取出最新的值
const setData = () => {
  midData.refrigerator =
    JSON.parse(localStorage.getItem("test")) || toRaw(testdata.value);
  // midData.refrigerator2 =
  //   JSON.parse(localStorage.getItem("test2")) || toRaw(testdata.value);
  // midData.refrigerator3 =
  //   JSON.parse(localStorage.getItem("test3")) || toRaw(testdata.value);
  midData.runtime =
    JSON.parse(localStorage.getItem("run")) || toRaw(state.yunxing);
  midData.energy =
    JSON.parse(localStorage.getItem("energy")) || toRaw(state.nenghao);
  midData.show = JSON.parse(localStorage.getItem("showTime"));
};

const machine_data = () => {
  tableStatus.value = "machineData";
};
function exportExcel() {
  //需给表格定义一个id或者类名
  console.log("1111111111", XLSX);
  let wb = XLSX.utils.table_to_book(document.querySelector("#table"));
  console.log("222");
  let wbout = XLSX.write(wb, {
    bookType: "xlsx",
    bookSST: true,
    type: "array",
  });
  try {
    FileSaver.saveAs(
      new Blob([wbout], { type: "application/octet-stream" }),
      "111.xlsx"
    ); //***是自己导出文件时的命名，随意
  } catch (e) {
    if (typeof console !== "undefined") console.log(e, wbout);
  }
  return wbout;
}
const operating_data = () => {
  tableStatus.value = "operatingData";
};

onMounted(() => {
  getYunXings();
  getLengjis();
  // 提前渲染dialog

  dialog.value.rendered = true;

  console.log("123", tree.value);
});

// 获取打印报表，运行数据
const getYunXings = async () => {
  let { data: res } = await YunXing();
  console.log("获取打印报表，运行数据", res);
  if (res.code == 200) {
    tableDataOperating.value = res.data.list;
  }
};

// 获取打印报表，冷机数据
const getLengjis = async () => {
  let { data: res } = await Lengji();
  console.log("获取打印报表，冷机数据", res);
  if (res.code == 200) {
    tableData.value = res.data.list;
  }
};

const qualified = () => [(tableStatus.value = "qualified")];
</script>

<style lang="less" scoped>
.box {
  display: flex;

  .card-css {
    flex: 1;
    width: 1760px;
    height: 817px;
    position: relative;

    .zhpj {
      position: absolute;
      border-bottom: 1px solid #d9deec;
      margin-right: 120px;
      margin-left: -20px;
      padding-left: 20px;
      padding-bottom: 20px;
      width: 100%;

      .zhpj-span {
        font-family: SourceHanSansSC-medium;
        font-weight: 700;
        color: #4d62a5;
        font-size: 20px;
      }
    }

    .table-css {
      display: flex;
      margin-top: 66px;
      justify-content: end;

      .select01 {
        width: 100px;
      }

      .select02 {
        width: 100px;
        margin-right: 20px;
        margin-left: 20px;
      }

      .btn-01 {
        margin-left: 20px;
        margin-right: 20px;
      }

      .el-button {
        background-color: #8faadc;
        border-color: #8faadc;
      }

      .btn-css {
        flex-grow: 1;
      }
    }
  }

  .table {
    margin-top: 20px;

    .el-checkbox {
      top: 3px;
      margin-left: 5px;
    }
  }

  .pagination {
    display: flex;
    justify-content: flex-end;
  }
}

:deep(.el-dialog__title) {
  color: #4d62a5;
}
:deep(.el-checkbox-group) {
  display: flex;
  flex-wrap: wrap;
}

.zdyDialog {
  width: 1000px;
}

.sava-btn {
  border-color: #8faadc;
  background-color: #8faadc;
}

.quxiao-btn {
  border-color: #cccccc;
  background-color: #cccccc;
  color: #fff;
}

:deep(.el-tree-node.is-expanded > .el-tree-node__children) {
  display: inline-flex;
}

.checkbox-div > div {
  margin-bottom: 10px;
}
.checkbox-div .el-checkbox {
  width: 40%;
}

:deep(.el-tree-node__content) {
  margin-bottom: 8px;
}

:deep(.el-dialog__body) {
  border-top: 1px solid #e7eaf3;
  border-bottom: 1px solid #e7eaf3;
}
</style>
